package com.concandthreads;

import java.util.concurrent.CountDownLatch;

/**
 * Created by nkrivko on 08.12.2014.
 */
public class CountDownLatchHolder {
    private final CountDownLatch countDownLatch = new CountDownLatch(2);
    int a = 0;

    public void doit() {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("run1");
                a = a - 1;
                countDownLatch.countDown();
                System.out.println("end run1");
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("run2");

                try {
                    Thread.currentThread().sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                a = a - 1;
                countDownLatch.countDown();
                System.out.println("end run2");
            }
        });

        thread1.start();
        thread2.start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(a);
            }
        }).start();
    }
}
